package org.gordonframework.site.layouts {
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	
	/**
	 * @author sampet
	 */
	public class GFlowLayout {

		public var direction:String;
		public var horizontalGap:Number;
		public var verticalGap:Number;
		public var wrap:Number;
		
		//TODO
		public var horizontalAlign:String;
		public var verticalAlign:String;
		public var jutified:Boolean;
		
		public function GFlowLayout(direction:String = "horizontal", horizontalGap:Number = 0, verticalGap:Number = 0, wrap:Number = -1) {
			this.direction = direction;
			this.horizontalGap = horizontalGap;
			this.verticalGap = verticalGap;
			this.wrap = wrap;
		}
		
		public function layoutContainer(container:DisplayObjectContainer):void {
			layoutHorizontal( container );
		}
		
		private function layoutHorizontal(container:DisplayObjectContainer):void {
			var rowY:Number = 0;
			var rowWidth:Number = 0;
			var rowHeight:Number = 0;
			 
			var child:DisplayObject;
			
			var layoutX:Number;
			var layoutIndex:uint = 0;
			var layoutChild:DisplayObject;

			for(var i:uint = 0; i < container.numChildren ; i++) {
				child = container.getChildAt( i );
				if(wrap > -1 && rowWidth + child.width > wrap) {
					//Layout row.
					layoutX = 0;
					while(layoutIndex < i) {
						layoutChild = container.getChildAt( layoutIndex++ );
						layoutChild.x = Math.round( layoutX );
						layoutChild.y = Math.round( rowY );
						layoutX += layoutChild.width + horizontalGap; 
					}
					//Start new row.
					layoutIndex = i;
					rowY += rowHeight + verticalGap;
					rowWidth = 0;
					rowHeight = 0;
				}
				rowWidth += child.width + horizontalGap;
				//update current row height.
				if(child.height > rowHeight) {
					rowHeight = child.height;
				}
			}
			//Layout last row.
			layoutX = 0;
			while(layoutIndex < i) {
				layoutChild = container.getChildAt( layoutIndex++ );
				layoutChild.x = Math.round( layoutX );
				layoutChild.y = Math.round( rowY );
				layoutX += layoutChild.width + horizontalGap; 
			}
		}

	}
}